package start.spring.basic.flowable.service.deploy.impl;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.flowable.common.engine.impl.db.SuspensionState;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.repository.ProcessDefinitionQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import start.spring.basic.flowable.dao.WfDeployFormMapper;
import start.spring.basic.flowable.entity.WfDeployForm;
import start.spring.basic.flowable.service.FlowableBaseServiceImpl;
import start.spring.basic.flowable.service.deploy.IWfDeployService;
import start.spring.basic.flowable.utils.flowable.ProcessUtils;
import start.spring.basic.flowable.vo.flowable.ProcessQuery;
import start.spring.basic.flowable.vo.flowable.WfDeployVo;
import start.spring.basic.page.PageQuery;
import start.spring.basic.page.PageResult;
import start.spring.basic.util.PageUtil;

/**
 * @author KonBAI
 * @createTime 2022/6/30 9:04
 */
@Service
public class WfDeployServiceImpl extends FlowableBaseServiceImpl implements IWfDeployService {
	
	@Autowired
    WfDeployFormMapper deployFormMapper;

    @Override
    public PageResult<WfDeployVo> queryPageList(PageQuery pageQuery, ProcessQuery processQuery) {
        // 流程定义列表数据查询
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery()
            .latestVersion()
            .orderByDeploymentId()
            .desc();
        // 构建搜索条件
        ProcessUtils.buildProcessSearch(processDefinitionQuery, processQuery);
        
        long pageTotal = processDefinitionQuery.count();
        if (pageTotal <= 0) {
        	return super.getPageResult(new PageUtil<>());
        }
        int offset = pageQuery.getSize() * (pageQuery.getCurrent() - 1);
        List<ProcessDefinition> definitionList = processDefinitionQuery.listPage(offset, pageQuery.getSize());
        
        List<WfDeployVo> deployVoList = new ArrayList<>(definitionList.size());
        for (ProcessDefinition processDefinition : definitionList) {
            String deploymentId = processDefinition.getDeploymentId();
            Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
            WfDeployVo vo = new WfDeployVo();
            vo.setDefinitionId(processDefinition.getId());
            vo.setProcessKey(processDefinition.getKey());
            vo.setProcessName(processDefinition.getName());
            vo.setVersion(processDefinition.getVersion());
            vo.setCategory(processDefinition.getCategory());
            vo.setDeploymentId(processDefinition.getDeploymentId());
            vo.setSuspended(processDefinition.isSuspended());
            // 流程部署信息
            vo.setCategory(deployment.getCategory());
            vo.setDeploymentTime(deployment.getDeploymentTime());
            deployVoList.add(vo);
        }
        
        PageUtil<WfDeployVo> pageUtil = new PageUtil<>();
        pageUtil.setCurrentPage(pageQuery.getCurrent());
        pageUtil.setNumPerPage(pageQuery.getSize());
        pageUtil.setTotalRecords(pageTotal);
        pageUtil.setResultList(deployVoList);
        return super.getPageResult(pageUtil);
    }

    @Override
    public PageResult<WfDeployVo> queryPublishList(PageQuery pageQuery, String processKey) {
        // 创建查询条件
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery()
            .processDefinitionKey(processKey)
            .orderByProcessDefinitionVersion()
            .desc();
        long pageTotal = processDefinitionQuery.count();
        if (pageTotal <= 0) {
        	return super.getPageResult(new PageUtil<>());
        }
        // 根据查询条件，查询所有版本
        int offset = pageQuery.getSize() * (pageQuery.getCurrent() - 1);
        List<ProcessDefinition> processDefinitionList = processDefinitionQuery
            .listPage(offset, pageQuery.getSize());
        List<WfDeployVo> deployVoList = processDefinitionList.stream().map(item -> {
            WfDeployVo vo = new WfDeployVo();
            vo.setDefinitionId(item.getId());
            vo.setProcessKey(item.getKey());
            vo.setProcessName(item.getName());
            vo.setVersion(item.getVersion());
            vo.setCategory(item.getCategory());
            vo.setDeploymentId(item.getDeploymentId());
            vo.setSuspended(item.isSuspended());
            return vo;
        }).collect(Collectors.toList());
//        Page<WfDeployVo> page = new Page<>();
//        page.setRecords(deployVoList);
//        page.setTotal(pageTotal);
//        return TableDataInfo.build(page);
        PageUtil<WfDeployVo> pageUtil = new PageUtil<>();
        pageUtil.setCurrentPage(pageQuery.getCurrent());
        pageUtil.setNumPerPage(pageQuery.getSize());
        pageUtil.setTotalRecords(pageTotal);
        pageUtil.setResultList(deployVoList);
        return super.getPageResult(pageUtil);
    }

    /**
     * 激活或挂起流程
     *
     * @param state 状态
     * @param definitionId 流程定义ID
     */
    @Override
    public void updateState(String definitionId, String state) {
        if (SuspensionState.ACTIVE.toString().equals(state)) {
            // 激活  false不操作流程实例
        	repositoryService.activateProcessDefinitionById(definitionId, false, null);
//            repositoryService.activateProcessDefinitionById(definitionId, true, null);
        } else if (SuspensionState.SUSPENDED.toString().equals(state)) {
            // 挂起 false不操作流程实例
        	repositoryService.suspendProcessDefinitionById(definitionId, false, null);
//            repositoryService.suspendProcessDefinitionById(definitionId, true, null);
        }
    }

    @Override
    public String queryBpmnXmlById(String definitionId) {
        InputStream inputStream = repositoryService.getProcessModel(definitionId);
        try {
            return IoUtil.readUtf8(inputStream);
        } catch (IORuntimeException exception) {
            throw new RuntimeException("加载xml文件异常");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<String> deployIds) {
        for (String deployId : deployIds) {
        	//删除
            repositoryService.deleteDeployment(deployId, true);
            deployFormMapper.delete(new LambdaQueryWrapper<WfDeployForm>().eq(WfDeployForm::getDeployId, deployId));
        }
    }
}
